package net.kucukcezve.tabu.stopwatch;

import java.util.*;

public class StopWatchThread extends Thread {

    private StopWatchObserver observer;
    boolean paused = true;
    boolean stopped = false;
    private Date startTime;
    private long totaltime = 0;

    public StopWatchThread(StopWatchObserver _observer) {
        this.observer = _observer;
    }

    // stops the thread
    public synchronized void killThread() {
        stopped = true;
    }

    // determines whether or not the thread should be running
    public synchronized boolean runThread() {
        return !stopped;
    }

    // starts the stopwatch after being paused
    public synchronized void startWatch() {

        if (startTime == null) {
            startTime = new Date();
        }

        paused = false;

        // wake up the thread
        notifyAll();
    }

    // pauses the stopwatch
    public synchronized void pauseWatch() {
        paused = true;
        Date pauseTime = new Date();
        totaltime = pauseTime.getTime() - startTime.getTime() + totaltime;

        // null out startTime so that on startWatch(), we get a new startTime
        startTime = null;
    }

    // resets the stopwatch
    public synchronized void resetWatch() {

        // reset startTime
        if (startTime != null) {
            startTime = null;
        }

        // reset totaltime
        totaltime = 0;

    }

    public synchronized boolean isPaused() {
        return paused;
    }

    private String getTime() {
        Calendar c = Calendar.getInstance();
        Date rightNow = new Date();
        c.setTime(new Date(rightNow.getTime() - startTime.getTime() + totaltime));

        int min = c.get(Calendar.MINUTE);
        int sec = c.get(Calendar.SECOND);
        int msec = c.get(Calendar.MILLISECOND);

        String smin;
        String ssec;
        String smsec;
        // massage the values

        if (min < 10) {
            smin = "0" + min;
        } else {
            smin = String.valueOf(min);
        }

        if (sec < 10) {
            ssec = "0" + sec;
        } else {
            ssec = String.valueOf(sec);
        }
        if (msec < 10) {
            smsec = "0" + msec;
        } else {
            smsec = String.valueOf(msec);
        }

        return smin + ":" + ssec + ":" + smsec;
    }

    public void run() {

        while (runThread()) {

            try {
                if (!isPaused()) {
                    try {
                        observer.timeUpdate(getTime());
                    } catch (Exception e) {
                    }
                    Thread.sleep(100);

                } else {
                    synchronized (this) {
                        wait();
                    }
                }
            } catch (InterruptedException e) {
            }
        }
    }
}
